import requests
from ..browser import browser_factory
from ..browser import cookie_manager
from ..exceptions import SpiderException
import random
import time
from ..config import config
from ..logger import logger

class SpiderBase:
    def __init__(self):
        self.session = requests.Session()
        self.cookie_manager = cookie_manager

    def _sync_cookies(self):
        self.session.cookies.update(
            self.cookie_manager.get_current_cookies()
        )

    def _create_headers(self):
        headers = {
            'User-Agent': random.choice(config.USER_AGENTS),
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
        }
        return headers

    def get(self, url) -> str:
        headers = {
            "accept": "text/html, application/json",
            "accept-language": "zh-CN,zh-TW;q=0.9,zh-HK;q=0.8,zh;q=0.7,en-US;q=0.6,en;q=0.5",
            "cache-control": "no-cache",
            "content-type": "application/json",
            "device-memory": "8",
            "dnt": "1",
            "downlink": "10",
            "dpr": "1.25",
            "ect": "4g",
            "origin": "https://www.amazon.com",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://www.amazon.com/sories/zgbs/amazon-devices/",
            "rtt": "50",
            "sec-ch-device-memory": "8",
            "sec-ch-dpr": "1.25",
            "sec-ch-ua": '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-ch-ua-platform-version": '"15.0.0"',
            "sec-ch-viewport-width": "1806",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
            "viewport-width": "1806",
            "x-requested-with": "XMLHttpRequest",
        }
        headers = self._create_headers()
        self.session.cookies.update(self.cookie_manager.get_current_cookies())
        err = None
        for _ in range(3):
            time.sleep(random.uniform(1, 3))
            try:
                response = self.session.post(url, headers=headers, timeout=config.REQUEST_TIMEOUT)  # 使用配置超时
                response.raise_for_status()
                logger.info(f'{url} 请求成功')
                return response.text
            except requests.exceptions.RequestException as err:
                logger.error(f'{url} 请求失败，正在重试... error={err}')
        else:
            raise SpiderException(f'{url} 请求失败')

    def post(self, url, json=None):
        headers = self._create_headers()
        self.session.cookies.update(self.cookie_manager.get_current_cookies())
        err = ''
        for _ in range(3):
            time.sleep(random.uniform(1, 3))
            try:
                response = self.session.get(
                    url, 
                    headers=headers, 
                    timeout=config.REQUEST_TIMEOUT,
                    params=json
                )
                response.raise_for_status()
                logger.info(f'{url} 请求成功')
                return response.text
            except requests.exceptions.RequestException as err:
                logger.error(f'{url} 请求失败, 参数{json}，正在重试... error={err}')
        else:
            raise SpiderException(f'{url} 请求失败')